package com.intelligentcar.springboot.service.serverImpl;

import com.intelligentcar.springboot.bean.Menu;
import com.intelligentcar.springboot.bean.Role;
import com.intelligentcar.springboot.mapper.RoleMapper;
import com.intelligentcar.springboot.service.RoleServer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class RoleServerImpl implements RoleServer {
    @Autowired
    private RoleMapper roleMapper;

    //查询角色表中的所有角色
    @Override
    public List<Role> selectrole() {
        return roleMapper.selectrole();
    }

    @Override
    public Map<String,Object> roleTable(Role role) {
        role.setPage((role.getPage()-1) * role.getLimit());
        Map<String,Object> map = new HashMap<>();
        map.put("roleList",roleMapper.roleTable(role));
        map.put("count",roleMapper.selectPageCount());
        return map;
    }

    @Override
    public boolean updateRole(Role role) {
        int i = roleMapper.updateRole(role);
        if (i>0) {
            return true;
        }else {
            return false;
        }
    }

    @Override
    public boolean updateRoleState(Role role) {
        int i = roleMapper.updateRoleState(role);
        if (i > 0) {
            return true;
        }else {
            return false;
        }
    }

    @Override
    public boolean insertRole(Role role) {
        String time =new SimpleDateFormat("yyyy-MM-dd-HH:mm:ss").format(new Date());
        role.setAddTime(time);
        int i = roleMapper.insertRole(role);
        Role role1 = roleMapper.selectRoleId(role);
        List<Menu> list = roleMapper.selectAllMenuId();
        List<Menu> menus = new ArrayList<>();
        for (Menu m: list) {
            Menu menu = new Menu();
            menu.setAddTime(time);
            menu.setMenuId(m.getMenuId());
            menu.setRoleId((int) role1.getRoleId());
            menus.add(menu);
        }
        int j = roleMapper.insertRolePower(menus);
        if (i > 0 && j > 0) {
            return true;
        }else {
            return false;
        }
    }

    @Override
    public Map<String, Object> selectRole(Role role) {
        role.setPage((role.getPage()-1) * role.getLimit());
        if (role.getRoleName() != "" && role.getRoleName() != null){
            role.setRoleName("%"+role.getRoleName()+"%");
        }
        Map<String,Object> map = new HashMap<>();
        List<Role> list = roleMapper.selectRole(role);
        map.put("roleList",list);
        map.put("count",roleMapper.selectedPageCount(role));
        return map;
    }

}
